package com.walterlife;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletDemo extends HttpServlet { 
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        boolean success = validateUser(username, password);

        try {
            // Write some content
            out.println("<html>");
            out.println("<head>");
            out.println("<title>MyFirstServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h2>Servlet MyFirstServlet at " + request.getContextPath() + "</h2>");

            out.println("<h2>Username: " + username + "</h2>");
            out.println("<h2>Password: " + password + "</h2>");
            if(success) {
                out.println("<h2>Welcome Friend</h2>");
            } else {
                out.println("<h2>Validate false!Please validate again!!</h2>");
            } 

            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close(); 
        }
    } 

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

    }

    public String getServletInfo() {
        return "MyFirstServlet";
    }

    public boolean validateUser(String username, String password) {
        if(username == null || password == null) {
            return false;
        } 

        if("walter".equals(username) && "walter".equals(password)) {
            return true;
        } 

        return false;
    } 
}
